<template>
	<view class="feeDeat">
		<view class="header">
			<view class="header-right" v-if="detailsForm.payStatus == 1">
				<view style="margin: 0 auto;font-weight: bold;">{{ `${homneForm.diner}到${homneForm.canteenName || ''}缴费证明` }}</view>
			</view>
			<view class="header-right">
				<text>付款状态</text>
				<view v-if="![6].includes(detailsForm.status)" :style="{
					color: statusList.find(res => { return res.status == detailsForm.payStatus }).color,
				}">
					{{statusList.find(res => { return res.status == detailsForm.payStatus }).label}}
				</view>
				<view v-else>
					已退款
				</view>
			</view>
			<view class="header-right">
				<text>申请人</text>
				<text>{{ detailsForm.fullName || '' }}</text>
			</view>
			<view class="header-right">
				<text>申请部门</text>
				<text>{{ detailsForm.deptName || '' }}</text>
			</view>
			<view class="header-right">
				<text>申请号码</text>
				<text>{{ detailsForm.applyPhone || '' }}</text>
			</view>
			<view class="header-right">
				<text>用餐人</text>
				<text>{{ detailsForm.diner || '' }}</text>
			</view>
			<view class="header-right">
				<text>单位名称</text>
				<text>{{ detailsForm.unitName || '' }}</text>
			</view>
			<view class="header-right">
				<text>用餐人号码</text>
				<text>{{ detailsForm.phone || '' }}</text>
			</view>
			<view class="header-right">
				<text>收款单位</text>
				<text>{{ detailsForm.payee || '' }}</text>
			</view>
			<view class="header-right">
				<text>用餐地点</text>
				<text>{{ detailsForm.canteenName || '' }}</text>
			</view>
			<view class="header-right">
				<text>用餐开始时间</text>
				<text>{{ detailsForm.diningStartTime || '' }}</text>
			</view>
			<view class="header-right">
				<text>用餐结束时间</text>
				<text>{{ detailsForm.diningEndTime || '' }}</text>
			</view>
			<!-- 用餐费用列表 -->
			<view v-for="(item, index) in diningExpenseList" :key="'dining-' + index" class="header-right">
				<text>{{ item.name }}</text>
				<text>{{ item.subtotal }}{{ item.expenseUnits }}</text>
			</view>
			<view class="header-right">
				<text>用餐金额</text>
				<text>{{ detailsForm.diningAmount+'元' || '' }}</text>
			</view>
			<!-- 其他费用列表 -->
			<view v-for="(item, index) in otherExpenseList" :key="'other-' + index" class="header-right">
				<text>{{ item.name }}</text>
				<text>{{ item.subtotal }}{{ item.expenseUnits }}</text>
			</view>
			<view class="header-right">
				<text>其他费用金额</text>
				<text>{{ detailsForm.othersAmount+'元' || '' }}</text>
			</view>
			<view class="header-right">
				<text>备注</text>  
				<text>{{ detailsForm.remark || '' }}</text>
			</view>
			<view class="header-right">
				<text>付款单号</text>
				<text>{{ detailsForm.merchantOrderNo || '' }}</text>
			</view>
			<view class="header-right">
				<text>付款时间</text>
				<text>{{ detailsForm.payTime || '' }}</text>
			</view>
			<view class="header-right">
				<text>创建时间</text>
				<text>{{ detailsForm.createTime || '' }}</text>
			</view>
			<view v-if="detailsForm.status == 6" class="header-right">
				<text>退款金额</text>
				<text>{{ detailsForm.refundPrice+'元' || '' }}</text>
			</view>
			<view v-if="detailsForm.status == 6" class="header-right">
				<text>退款时间</text>
				<text>{{ detailsForm.refundPriceTime || '' }}</text>
			</view>
		</view>
		<view class="footer">
			<view style="text-align: center;font-size: 26rpx;color: #ff0000;">
				<!-- {{ description.description || '' }} -->
				如对本次支付金额存在疑虑，可在支付成功<text style="" > {{statusOptions}}</text>天内发起退款。
			</view>
			<view class="header-total-box">
				<!-- <view class="header-total">
					<text>合计：</text>
					<text style="color: red;">￥{{ detailsForm.totalAmount }}</text>
				</view> -->
				<view style="display: flex;">
					<view class="total-label" style="display: flex;align-items: center;">合计：</view>
					<yuanPrice :value="detailsForm.totalAmount" />
				</view>
				<view class="header-total-button">
					<view v-if="!['6'].includes(detailsForm.status)">
						<u-button size="mini" v-if="detailsForm.status == '1' && canApplyRefund()" @click="openRefundPopup(1)" style="font-size: 26rpx;">申请退款</u-button>
						<u-button size="mini" v-else-if="detailsForm.status == '4'"
							@click="openRefundPopup(2)" style="font-size: 26rpx;">退款审核中</u-button>
						<u-button size="mini" v-else-if="detailsForm.status == '7'"
							@click="openRefundPopup(4)" style="font-size: 26rpx;">退款未通过</u-button>
					</view>
					<u-button v-if="detailsForm.payStatus == 1" size="mini" type="primary"
						@click="handlePay" style="font-size: 26rpx;">下载付款明细（PDF）</u-button>
				</view>
			</view>
		</view>
		<!-- 申请退款 -->
		<u-popup v-model="refundPopupVisible" mode="center" round="10" @close="closeRefund">
			<view class="refund-dialog">
				<view class="refund-title">
					{{ getDialogTitle() }}
				</view>
				<view class="refund-amount-row" v-if="showRefundAmountRow()">
					<view style="display: flex;align-items: center;"> <view style="width: 180rpx;">可退款金额：</view><yuanPrice :value="detailsForm.totalAmount" /></view>
					<view class="refund-all" @click="refundAll" v-if="canEdit()">全部退款</view>
				</view>
				<u-form :model="refundForm" ref="refundForm" label-width="180rpx">
					<u-form-item label="退款金额" prop="price" required>
						<u-input v-model="refundForm.price" placeholder="请输入退款金额" type="digit"
							@input="handlePriceInput" :disabled="!canEdit()" />
					</u-form-item>
					<u-form-item label="退款原因" prop="remark" required>
						<template v-if="!canEdit()">
							<view style="word-break: break-all;word-wrap: break-word;">{{ refundForm.remark }}</view>
						</template>
						<template v-else>
							<u-input v-model="refundForm.remark" placeholder="请说明退款原因" type="text" maxlength="100" />
						</template>
					</u-form-item>
					<!-- 审核状态 -->
					<u-form-item v-if="showAuditStatus()" label="审核状态">
						<view>{{ getAuditStatusText() }}</view>
					</u-form-item>
					<!-- 驳回原因 -->
					<u-form-item v-if="showRejectReason()" label="驳回原因">
						<view class="reject-reason-text">{{ detailsForm.refundRejectReason }}</view>
					</u-form-item>
				</u-form>
				
				<!-- 按钮区域 -->
				<view v-if="showReapplyButton()" class="refund-buttons-center">
					<u-button type="primary" @click="reapplyCli">重新申请</u-button>
				</view>
				<view v-else-if="showSubmitButtons()" class="refund-buttons">
					<u-button type="default" @click="closeRefund">取消</u-button>
					<u-button type="primary" @click="submitRefund">提交</u-button>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
import {
	uploadFile
} from '@/settings'
import {
	getInformation
} from '@/api/meal/home.js'
import {
	getPdfOut,
	getInfo,
	getApplyRefund,
	getDicts
} from '@/api/meal/feeDetails'
import yuanPrice from '@/components/yuanPrice/yuanPrice.vue'
export default {
	components: {
		yuanPrice
	},
	data() {
		return {
			detailsForm: {},
			orderId: '',
			refundPopupVisible: false,
			maxRefundAmount: 666.00,
			refundForm: {
				id: '',
				price: '',
				remark: ''
			},
			homneForm: {},
			diningExpenseList: [], // 用餐费用列表
			otherExpenseList: [], // 其他费用列表
			statusList: [{
				label: '待支付',
				status: 0,
				color: '#f5a031'
			}, {
				label: '已支付',
				status: 1,
				color: '#19be6b'
			}, {
				label: '已取消',
				status: 2,
				color: '#c2c2c2'
			}],
			rules: {
				price: [{
					required: true,
					message: '请输入退款金额',
					trigger: ['blur', 'change']
				}],
				remark: [{
					required: true,
					message: '请输入退款原因',
					trigger: ['blur', 'change']
				}],
			},
			isCoum: false,
			description: {},
			statusOptions: null,
			isReapplying: false, // 是否正在重新申请状态
		}
	},
	onReady() {
		this.$nextTick(() => {
			if (this.$refs.refundForm && this.rules) {
				this.$refs.refundForm.setRules(this.rules);
			}
		});
	},
	onLoad(options) {
		this.homneForm = options
		this.orderId = options.id
		this.infutatText()
		this.getForDetails()
	},
	methods: {
		/**获取详情 */
		getForDetails() {
			getInfo({
				id: this.orderId
			}).then((res) => {
				if (res.data.code == 200) {
					this.detailsForm = res.data.data || {}
					
					// 分离用餐费用和其他费用
					this.separateExpenseList()
				}
			})
		},
		
		/**分离费用列表 */
		separateExpenseList() {
			if (!this.detailsForm.expenseDetailList) {
				this.diningExpenseList = []
				this.otherExpenseList = []
				return
			}
			
			// 根据费用类型分离列表
			this.diningExpenseList = this.detailsForm.expenseDetailList.filter(item => 
				item.isDefault === '0'
			)
			this.otherExpenseList = this.detailsForm.expenseDetailList.filter(item => 
				item.isDefault === '1'
			)
		},
		/**获取协议 */
		infutatText() {
			getDicts("refund_config").then(response => {
				if (response.data.code == 200) {
					const day = response.data.data.find(item => item.dictLabel === 'day');
					// if (response.data.data.dictLabel == 'day') {
					this.statusOptions = day.dictValue
					// }

				}
			});
		},

		/**输入框限制 */
		handlePriceInput(val) {
			// 非法输入自动设为空字符串
			if (isNaN(input)) {
				this.refundForm.price = ''
				return
			}

			// 限制不能超过最大值
			if (input > max) {
				this.refundForm.price = ''
			} else {
				this.refundForm.price = val
			}
		},
		/**申请退款 */
		openRefundPopup(e) {
			this.refundForm.id = this.detailsForm.id
			this.isReapplying = false // 重置重新申请状态
			
			if (e == 2) { // 退款审核中状态
				this.refundForm.price = this.detailsForm.refundPrice
				this.refundForm.remark = this.detailsForm.refundPriceDesc
			} else if (e == 4) { // 退款未通过状态
				this.isCoum = true
				this.refundForm.price = this.detailsForm.refundPrice
				this.refundForm.remark = this.detailsForm.refundPriceDesc
			} else if (e == 1) { // 已支付状态，可以申请退款
				this.refundForm.price = ''
				this.refundForm.remark = ''
			}
			this.refundPopupVisible = true;
		},
		/**重新申请 */
		reapplyCli() {
			this.refundForm.price = '';
			this.refundForm.remark = '';
			this.isCoum = false
			this.isReapplying = true // 设置为重新申请状态
		},
		
		/**获取弹窗标题 */
		getDialogTitle() {
			if (this.detailsForm.status == '4') {
				return '退款审核中'
			} else if (this.detailsForm.status == '7' && !this.isReapplying) {
				return '退款未通过'
			} else {
				return '发起退款'
			}
		},
		
		/**是否可以编辑 */
		canEdit() {
			// 已支付状态(1)或者正在重新申请时可以编辑
			return this.detailsForm.status == '1' || this.isReapplying
		},
		
		/**是否显示退款金额行 */
		showRefundAmountRow() {
			// 所有状态都显示退款金额行
			return true
		},
		
		/**是否显示审核状态 */
		showAuditStatus() {
			// 非已支付状态且非重新申请状态时显示
			return this.detailsForm.status != '1' && !this.isReapplying
		},
		
		/**获取审核状态文本 */
		getAuditStatusText() {
			console.log('this.detailsForm.status',this.detailsForm.status);
			
			switch(this.detailsForm.status) {
				case '4':
					return '退款审核中'
				case '6':
					return '退款通过'
				case '7':
					return '退款驳回'
				default:
					return ''
			}
		},
		
		/**是否显示驳回原因 */
		showRejectReason() {
			// 退款驳回状态且非重新申请状态时显示
			return this.detailsForm.status == '7' && !this.isReapplying
		},
		
		/**是否显示重新申请按钮 */
		showReapplyButton() {
			// 退款驳回状态且非重新申请状态时显示
			return this.detailsForm.status == '7' && !this.isReapplying
		},
		
		/**是否显示提交按钮 */
		showSubmitButtons() {
			// 已支付状态或重新申请状态时显示提交按钮
			return this.detailsForm.status == '1' || this.isReapplying
		},
		
		/**是否可以申请退款 */
		canApplyRefund() {
			if (!this.detailsForm.payTime || !this.statusOptions) {
				return false
			}
			
			// 获取付款时间
			const payTime = new Date(this.detailsForm.payTime)
			const currentTime = new Date()
			
			// 计算时间差（天数）
			const timeDiff = currentTime.getTime() - payTime.getTime()
			const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24))
			
			// 判断是否在允许退款的天数范围内
			return daysDiff <= parseInt(this.statusOptions)
		},
		closeRefund() {
			this.refundPopupVisible = false;
			this.refundForm.price = '';
			this.refundForm.remark = '';
			this.isReapplying = false; // 重置重新申请状态
			this.isCoum = false; // 重置状态
		},
		refundAll() {
			this.refundForm.price = this.detailsForm.totalAmount.toFixed(2);
		},
		submitRefund() {
			this.$refs.refundForm.validate(valid => {
				if (valid) {
					getApplyRefund(this.refundForm).then((res) => {
						if (res.data.code == 200) {
							uni.showToast({
								title: '提交成功',
								icon: 'success'
							});
							this.closeRefund();
							// 刷新详情数据
							this.getForDetails();
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					})
				}
			})
		},
		/**确认退款 */
		confirmRefund() {
			uni.showToast({
				title: '退款申请已提交',
				icon: 'success'
			});
			this.close();
		},
		/**下载付款明细 */
		handlePay() {
			console.log('开始下载PDF，订单ID:', this.orderId);
			getPdfOut(this.orderId).then(res => {
				console.log('getPdfOut API 返回结果:', res);
				if (res.data.code == 200) {
					const downloadUrl = uploadFile + res.data.msg;
					console.log('准备下载文件，完整URL:', downloadUrl);
					this.downloadAndSaveFile(downloadUrl);
				} else {
					console.error('获取PDF URL失败:', res);
					uni.showToast({
						title: '获取PDF失败',
						icon: 'none'
					});
				}
			}).catch(err => {
				console.error('getPdfOut API 调用失败:', err);
				uni.showToast({
					title: '获取PDF失败',
					icon: 'none'
				});
			});
		},
		/**下载文件 */
		// 方法：下载并保存文件
		downloadAndSaveFile(fileUrl) {
			uni.downloadFile({
				url: fileUrl,
				success: (res) => {
					if (res.statusCode === 200) {
						console.log(res);
						uni.shareFileMessage({
							filePath: res.tempFilePath,
							fileName: `${this.homneForm.diner}到${this.homneForm.canteenName}用餐缴费证明.pdf`,
							success: () => {
								console.log('文件已分享，可保存到手机');
							},
							fail: (err) => {
								console.error('文件分享失败', err);
							}
						});
					} else {
						console.error('分享失败，状态码:', res.statusCode);
						uni.showToast({
							title: '文件下载失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error("分享失败", err);
					uni.showToast({
						title: '文件下载失败',
						icon: 'none'
					});
				}
			});
			// uni.downloadFile({
			// 	url: fileUrl,
			// 	success: (res) => {
			// 		if (res.statusCode === 200) {
			// 			// 获取微信文件管理器
			// 			const fs = uni.getFileSystemManager();
			// 			const tempPath = res.tempFilePath;
			// 			const fileName = `${this.homneForm.diner}到${this.homneForm.canteenName}用餐缴费证明`;
			// 			const savePath = `${wx.env.USER_DATA_PATH}/${fileName}`;

			// 			fs.saveFile({
			// 				tempFilePath: tempPath,
			// 				filePath: savePath,
			// 				success: (saveRes) => {
			// 					console.log('保存成功：', saveRes.savedFilePath);

			// 					// 可选：立即打开文件（PDF/Word等）
			// 					uni.openDocument({
			// 						filePath: saveRes.savedFilePath,
			// 						success: () => {
			// 							console.log('文档打开成功');
			// 						},
			// 						fail: (err) => {
			// 							console.error('打开失败', err);
			// 						}
			// 					});
			// 				},
			// 				fail: (err) => {
			// 					console.error('保存失败：', err);
			// 				}
			// 			});
			// 		} else {
			// 			console.error('下载失败，状态码：', res.statusCode);
			// 		}
			// 	},
			// 	fail: (err) => {
			// 		console.error('下载出错：', err);
			// 	}
			// });
		},
	}
}
</script>

<style lang="scss">
.feeDeat {
	min-height: 100vh;
	// padding: 0 20rpx;
	padding: 0 20rpx 186rpx; // 避免内容被底部按钮遮挡
}

.header {
	// margin-bottom: 30px;
}

.header-right {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	min-height: 80rpx;
	padding: 20rpx 0;
	
	text {
		&:first-child {
			width: 180rpx;
			flex-shrink: 0;
			color: #333;
		}
		
		&:last-child {
			flex: 1;
			text-align: right;
			word-break: break-all;
			word-wrap: break-word;
		}
	}
}

.header-total-box {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 0;
}

.total-label {
	display: flex;
	align-items: center;
}

.header-total-button {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.footer {
	position: fixed;
	z-index: 999;
	bottom: 0;
	left: 0;
	right: 0;
	// height: 140rpx;
	background-color: #fff;
	// display: flex;
	// align-items: center;
	// padding: 0 30rpx;
	padding: 0 20rpx;
	padding-bottom: 35rpx;
	border-top: 1rpx solid #eee;
}

.refund-dialog {
	width: 600rpx;
	padding: 30rpx;
	background: #fff;
	border-radius: 20rpx;
}

.refund-title {
	font-size: 36rpx;
	font-weight: bold;
	text-align: center;
	margin-bottom: 30rpx;
}

.refund-amount-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
	font-size: 28rpx;
}

.refund-all {
	color: #2979ff;
	font-size: 28rpx;
}

.refund-buttons {
	display: flex;
	justify-content: space-between;
	margin-top: 30rpx;

	u-button {
		width: 45%;
		height: 70rpx;
	}
}

.refund-buttons-center {
	display: flex;
	justify-content: center;
	margin-top: 30rpx;

	u-button {
		width: 60%;
		height: 70rpx;
	}
}

.reject-reason-text {
	word-break: break-all;
	word-wrap: break-word;
	white-space: pre-wrap;
	line-height: 1.6;
	max-width: 100%;
	overflow-wrap: break-word;
}
::v-deep .u-size-mini{
	font-size: 26rpx !important;
	height: 64rpx !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
}
</style>